package com.ruoyi.web.controller.douyin;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.system.alipay.AlipayConstants;
import com.ruoyi.system.alipay.XmlPayUtil;
import com.ruoyi.system.domain.bo.DyIndexBo;
import com.ruoyi.system.domain.bo.DyOrderGoodsBo;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.vo.AlipayResultVo;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.bo.DyOrderBo;
import com.ruoyi.system.service.IDyOrderService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单
 *
 * @author ruoyi
 * @date 2024-06-20
 */
@Validated
@RequiredArgsConstructor
@RestController
@Slf4j
@RequestMapping("/system/order")
public class DyOrderController extends BaseController {

    private final IDyOrderService iDyOrderService;

    /**
     * 查询订单列表
     */
    @SaCheckPermission("system:order:list")
    @GetMapping("/list")
    public TableDataInfo<DyOrderVo> list(DyOrderBo bo, PageQuery pageQuery) {
        LoginUser loginUser = getLoginUser();
        return iDyOrderService.queryPageList(bo, pageQuery,loginUser);
    }

    /**
     * 导出订单列表
     */
    @SaCheckPermission("system:order:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DyOrderBo bo, HttpServletResponse response) {
        List<DyOrderVo> list = iDyOrderService.queryList(bo);
        List<DyOrderExcelVo> orderExcelVos = new ArrayList<>();
        for (DyOrderVo item : list){
            DyOrderExcelVo orderExcelVo = new DyOrderExcelVo();
            BeanUtil.copyProperties(item,orderExcelVo);
            orderExcelVos.add(orderExcelVo);
        }
        ExcelUtil.exportExcel(orderExcelVos, "订单", DyOrderExcelVo.class, response);
    }

    /**
     * 获取订单统计信息
     */
    @GetMapping("/getOrderSum")
    public R<DyOrderSumVo> getOrderSum(DyOrderBo bo) {
        LoginUser loginUser = getLoginUser();
        return R.ok(iDyOrderService.getOrderSum(bo, loginUser));
    }

    /**
     * 获取首页订单统计信息
     */
    @GetMapping("/getIndexIncomeSum")
    public R<List<OrderIndexIncomeSumVo>> getIndexIncomeSum() {
        LoginUser loginUser = getLoginUser();
        log.info("getIndexIncomeSum,loginUser:{}", JsonUtils.toJsonString(loginUser));
        return R.ok(iDyOrderService.getIndexIncomeSum(loginUser));
    }

    /**
     * 获取首页公司统计信息
     */
    @GetMapping("/getIndexCompanySum")
    public R<List<OrderIndexCompanySumVo>> getIndexCompanySum(DyIndexBo bo) {
        log.info("getIndexCompanySum,bo:{}", JsonUtils.toJsonString(bo));
        LoginUser loginUser = getLoginUser();
        log.info("getIndexCompanySum,loginUser:{}", JsonUtils.toJsonString(loginUser));
        bo.setLoginUser(loginUser);
        return R.ok(iDyOrderService.getIndexCompanySum(bo));
    }

    /**
     * 获取订单支付信息
     */
    @GetMapping("/addOrderPay")
    @SaIgnore
    public R<List<String>> addOrderPay(@Validated(AddGroup.class) DyOrderGoodsBo bo) {
        return R.ok(iDyOrderService.addOrderPay(bo));
    }

    @GetMapping("/testOrderPay")
    public R<List<String>> testOrderPay() {
        log.info("testOrderPay");
        return R.ok(iDyOrderService.buildOrderNo());
    }

    /**
     * 获取订单支付信息
     */
    @GetMapping("/addOrderPayDemoTest")
    public R<List<String>> addOrderPayDemoTest(DyOrderGoodsBo bo) {
        log.info("addOrderPayDemoTest,bo:{}", JsonUtils.toJsonString(bo));
        return R.ok(iDyOrderService.addOrderPayDemoTest(bo));
    }

    /**
     * 支付宝支付回调
     */
    @PostMapping("/backOrderPay")
    @SaIgnore
    public String backOrderPay(@RequestParam("out_trade_no") String outTradeNo,
                                       @RequestParam("trade_status") String tradeStatus,
                                       @RequestParam("sign") String sign,
                                       @RequestParam("trade_no") String tradeNo) {
        log.info("backOrderPay,request in");
        log.info("backOrderPay,outTradeNo:{}",outTradeNo);
        log.info("backOrderPay,tradeStatus:{}",tradeStatus);
        log.info("backOrderPay,tradeNo:{}",tradeNo);

        String backed = "fail";

        // 验证签名
        boolean signVerified = verifySign(sign); // 实现签名验证的方法
        if (!signVerified) {
            return backed;
        }

        if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
            backed = iDyOrderService.backOrderPay(outTradeNo, tradeNo);
        }

        return backed;
    }

    /**
     * 验证签名
     * @param sign
     * @return
     */
    private boolean verifySign(String sign) {
        // 实现签名验证逻辑
        // 通常需要使用支付宝公钥和参数及支付宝提供的签名算法
        return true; // 假设验证通过
    }

    /**
     * 获取订单详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:order:query")
    @GetMapping("/{id}")
    public R<DyOrderVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iDyOrderService.queryById(id));
    }

    /**
     * 新增订单
     */
    @SaCheckPermission("system:order:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DyOrderBo bo) {
        return toAjax(iDyOrderService.insertByBo(bo));
    }

    /**
     * 修改订单
     */
    @SaCheckPermission("system:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DyOrderBo bo) {
        return toAjax(iDyOrderService.updateByBo(bo));
    }

    /**
     * 删除订单
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:order:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iDyOrderService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 退款订单
     */
    @PostMapping("/refundOrder")
    public R<Void> refundOrder(@RequestBody DyOrderBo bo) {
        return toAjax(iDyOrderService.refundOrder(bo));
    }

    /**
     * 重置
     */
    @PostMapping("/resetCode")
    public R<Void> resetCode(@RequestBody DyOrderBo bo) {
        return toAjax(iDyOrderService.resetCode(bo));
    }

    /**
     * 根据order 支付号 查询订单
     */
    @PostMapping("/getOrderInfoByTradeNo")
    @SaIgnore
    public R<DyOrderVo> getOrderInfoByTradeNo(@RequestBody DyOrderBo bo) {
        DyOrderVo dyOrderVo = iDyOrderService.getOrderInfoByTradeNo(bo);
        return R.ok(dyOrderVo);
    }

    /**
     * 投诉订单
     */
    @PostMapping("/complaintOrder")
    public R<Void> complaintOrder(@RequestBody DyOrderBo bo) {
        return toAjax(iDyOrderService.complaintOrder(bo));
    }
}
